'use strict';
var fs = require('fs');
var path = require('path');
var TChannel = require('tchannel');
var HyperbahnClient = require('tchannel/hyperbahn/');
var rootChannel = TChannel();
var thrift = require('thrift');


var hyperbahnClient = HyperbahnClient({
    tchannel: rootChannel,
    serviceName: 'client',
    hostPortList: ['172.30.32.88:5001', '172.30.32.88:5002'],
        hardFail: true,
    reportTracing: false, 
});
const requestChannel = (hyperbahnClient, opt) => {
	console.log(opt.serverName);
  return new Promise((resolve, reject) => {
    var keyChan = hyperbahnClient.getClientChannel({
              serviceName: opt.serverName //'process_config_service' 
        });
        var keyThrift = rootChannel.TChannelAsThrift({
            entryPoint: path.join(__dirname, 'thrift/core.order.thrift'),
            channel: keyChan
        });
        // var t1 = new Date().getTime();
        // var buf1 = new Buffer();
        // console.log(t1.toString());
        // console.log(t1);
        // var buf = Buffer.from(opt.param);
        // var buf = new Buffer("data");
            // var parameter = {
            //     file: buf
            // };
        console.log(opt.param);
        keyThrift.request({
                 // serviceName: 'process_config_service',
                 timeout: 50000,
                 hasNoParent: true
              }).send(opt.method, null,   opt.param, // opt.param, //{ //'ProcessServerService::getServiceList',null , {
                    //   "orderbean":""
                    // },
                     function onResponseresolve(err, resp) {
                        
                        // console.log('got response', err,resp);
                    if (err) {
                    	
                    	reject(err);
                         
                        // return err;
                    } else {
                    	//console.log('got response', resp);
                    	resolve(resp);
                         
                        // return resp.body;
                    }
                    // rootChannel.close();
                });
	});
};
var reqChannel = async (hyperbahnClient, opt) => {
	try{
		var data = await requestChannel(hyperbahnClient, opt);
       

        
		// console.log('end');
		return data;
	} catch (e) {
		 // console.log('got error', e);	
		 return e;
	}
}
module.exports = {
    * requestThriftChannel(serverName, method, param) {
		var resp = yield reqChannel(hyperbahnClient, {serverName, method, param});
		console.log(' resp', resp);
        return resp;

    },
    

};

